<template>
  <el-dialog
    v-model="dialogVisible"
    v-if="load"
    :title="title"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    width="1000"
    :before-close="handleClose"
    :z-index="2000"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="formRule"
      label-align="right"
      label-width="90"
      size="default"
      :label-position="handleType == 'view' ? 'right' : 'top'"
    >
      <div class="sampleTitle">样品单信息</div>
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="样品单类型：" label-width="100">
            <template v-if="handleType == 'view'">
              {{ form.sample_type_text }}
            </template>
            <template v-else>
              <el-radio-group v-model="form.sample_type" class="ml-4">
                <el-radio
                  v-for="(item, index) in options['sample.Sample']?.[0].sampleTypeText"
                  :key="index"
                  :label="item.value"
                  >{{ item.label }}</el-radio
                >
              </el-radio-group>
            </template>
          </el-form-item>
        </el-col>
      </el-row>
      <div class="sampleTitle">采购信息</div>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="目的仓库：">
            <template v-if="handleType == 'view'">
              {{ form.warehouse_id_text }}
            </template>
            <template v-else>
              <SelectFilterWarehouse
                class="w-full"
                v-model="form.warehouse_id"
                placeholder="请选择"
              >
              </SelectFilterWarehouse>
            </template>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="供应商：">
            <template v-if="handleType == 'view'">
              {{ form.supplier_id_text }}
            </template>
            <template v-else>
              <select-supplie
                class="w-full"
                v-model="form.supplier_id"
                placeholder="请选择"
                disabled
              ></select-supplie>
            </template>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="采购人员：">
            <template v-if="handleType == 'view'">
              {{ form.purchaser_id_text }}
            </template>
            <template v-else>
              <select-personnel
                class="w-full"
                v-model="form.purchaser_id"
                placeholder="采购人员"
              ></select-personnel>
            </template>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="运营人员：" prop="status">
            <template v-if="handleType == 'view'">
              {{ form.operation_user_ids_text && form.operation_user_ids_text.join(",") }}
            </template>
            <template v-else>
              <select-personnel
                class="w-full"
                :multiple="true"
                v-model="form.operation_user_ids"
                placeholder="请选择"
              ></select-personnel>
            </template>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="运费：">
            <template v-if="handleType == 'view'">{{ form.freight }}</template>
            <el-input
              v-else
              v-model.trim="form.freight"
              placeholder="请输入"
              clearable
              style="width: 384px"
              oninput="value=value.replace(/[^\d.]/g,'').replace(/^(\d*\.?\d{0,2}).*/,'$1')"
            >
              <template #append>
                <el-button type="primary" style="font-weight: 700">CNY</el-button>
              </template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="总金额：">
            <template v-if="handleType == 'view'">{{ totalSummer }}</template>
            <el-input
              v-else
              v-model="totalSummer"
              placeholder="请输入"
              clearable
              disabled
            >
              <template #append>
                <el-button type="primary" style="font-weight: 700">CNY</el-button>
              </template>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="备注：">
        <template v-if="handleType == 'view'">{{ form.procurement_remarks }}</template>
        <el-input
          v-else
          v-model="form.procurement_remarks"
          :rows="4"
          type="textarea"
          placeholder="请输入"
        />
      </el-form-item>
      <template v-if="handleType == 'edit'">
        <div
          style="
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin: 16px 0 12px;
          "
        >
          <div class="sampleTitle">物流信息</div>
          <div>
            <div
              class="base-text-color"
              style="font-size: 14px; cursor: pointer"
              @click="goFun"
            >
              点击跳转【快递100】
            </div>
          </div>
        </div>
        <el-form-item label="物流追踪号">
          <VGroup class="w-full">
            <el-input
              v-model.trim="formOne.materialFlowInp"
              placeholder="请输入"
              clearable
              style="margin-left: -1px"
            >
              <template #append>
                <el-button
                  style="font-weight: 700; color: #fff; height: 40px; background: #3487ff"
                  @click="entryNumber"
                  >录入追踪号</el-button
                >
              </template>
            </el-input>
          </VGroup>
        </el-form-item>
        <div
          class="flex flex-col mb-4"
          v-for="(item, index) in form.tracking_nums"
          :key="index"
        >
          <div class="text-sm flex items-center">
            <span style="margin-left: 4px">{{ item.company_name }}</span>
            <span
              class="base-text-color"
              style="margin: 0 16px; cursor: pointer"
              @click="handleSearchOrder"
              >{{ item.cogistics_tracking_number }}</span
            >
            <svg-icon
              class="base-red-color text-lg"
              icon-class="del"
              @click="logisticsVisDel(index)"
            ></svg-icon>
          </div>
        </div>
      </template>
      <div
        style="
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin: 24px 0 12px;
        "
      >
        <div class="sampleTitle">商品信息</div>
        <div>
          <el-button type="primary" v-if="handleType != 'view'" @click="addSampleListFun"
            >添加商品</el-button
          >
        </div>
      </div>
      <vxe-table :align="allAlign" ref="tableRef" :data="form.product_list" height="300">
        <vxe-column type="seq" width="60" title="序号"></vxe-column>
        <vxe-column title="产品图片" width="80">
          <template #default="{ row }">
            <VImage
              :src="row.attr_img_watermark || row.attr_img"
              :width="52"
              :height="52"
            ></VImage>
          </template>
        </vxe-column>
        <vxe-column title="SKU" width="100">
          <template #default="{ row }">
            <div>
              <span>{{ row.goods_sku }}</span>
            </div>
          </template>
        </vxe-column>
        <vxe-column title="产品名称" min-width="150">
          <template #default="{ row }">
            <vText :value="row.sku_cn_title" :line="3"></vText>
          </template>
        </vxe-column>
        <vxe-column title="采购数量" width="80">
          <template #default="{ row }">
            <template v-if="handleType != 'view'">
              <el-input
                type="text"
                v-model="row.purchase_quantity"
                oninput="value=value.replace(/[^\d]/g,'')"
              ></el-input>
            </template>
            <template v-else>{{ row.purchase_quantity }}</template>
          </template>
        </vxe-column>
        <vxe-column title="采购单价" width="120">
          <template #default="{ row }">
            <!-- <el-input
              type="text"
              v-model="row.purchase_price"
              oninput="value=value.replace(/[^\d.]/g,'').replace(/^(\d*\.?\d{0,2}).*/,'$1')"
            ></el-input> -->
            {{ row.purchase_price }}
          </template>
        </vxe-column>
        <vxe-column title="供应商报价" width="180">
          <template #default="{ row }">
            <div>
              采购未税报价：<dataAuthority
                auth="unit_price"
                :value="row.supplier_quotation"
              ></dataAuthority>
            </div>
            <div>
              采购未税价：<dataAuthority
                auth="purchase_untaxed_price"
                :value="row.purchase_untaxed_price"
              ></dataAuthority>
            </div>
            <div>
              采购含税价：<dataAuthority
                auth="unit_price_tax"
                :value="row.unit_price_tax"
              ></dataAuthority>
            </div>
          </template>
        </vxe-column>
        <vxe-column title="金额/CNY" width="85">
          <template #default="{ row }">
            <div>
              <span>{{ calculatePrice(row) }} {{ row.currency }}</span>
            </div>
          </template>
        </vxe-column>
        <vxe-column
          title="操作"
          fixed="right"
          width="60"
          align="center"
          v-if="handleType != 'view'"
        >
          <template #default="{ rowIndex }">
            <div style="color: red; cursor: pointer" @click="delFun(rowIndex)">删除</div>
          </template>
        </vxe-column>
      </vxe-table>
    </el-form>

    <template #footer>
      <div class="flex justify-center items-center py-2">
        <template v-if="handleType !== 'view'">
          <el-button @click="() => handleClose(true)">取消</el-button>
          <el-button type="primary" :loading="loading" @click="sampleSaveFun">
            保存
          </el-button>
        </template>
        <template v-else>
          <el-button @click="() => handleClose(true)">关闭</el-button>
        </template>
      </div>
    </template>
  </el-dialog>
  <addSampleList
    ref="addSampleListRef"
    :list="form.product_list"
    :supplier_id="form.supplier_id"
    @addSampleListQuery="addSampleListQuery"
  />
  <el-dialog
    v-model="logisticsVisible"
    :before-close="handleClose1"
    :close-on-click-modal="false"
    :z-index="2000"
  >
    <div
      style="
        width: 500px;
        height: 400px;
        background-color: #fff;
        border-radius: 4px;
        font-size: 14px;
        padding: 20px;
        box-sizing: border-box;
        position: relative;
      "
    >
      <div class="triangle" />
      <div style="color: #0a1431; font-weight: 700">物流轨迹详情</div>
      <div style="color: #3a4259; margin-top: 20px">快递单号：SF35326208912</div>
      <div style="color: #3a4259; margin: 8px 0">
        当前状态：<span style="color: #3366f1">揽件</span>
      </div>
      <div style="color: #3a4259">轨迹详情：</div>
      <div style="position: absolute; top: 122px; left: 88px">
        <el-scrollbar height="250px">
          <div
            class="clearfix"
            :style="{
              position: 'relative',
              marginBottom: item != 20 ? '16px' : '0',
            }"
            v-for="item of 20"
            :key="item"
          >
            <div class="fl" style="margin-top: 12px">
              <i style="font-size: 10px !important" class="dk-iconfont icon-ArrowDown" />
            </div>
            <div class="fl" style="margin-left: 12px">
              <div>
                <span
                  v-if="item == 1"
                  style="
                    width: 32px;
                    height: 16px;
                    background: #ff609e;
                    color: #fff;
                    margin-right: 4px;
                    display: inline-flex;
                    font-size: 10px;
                    justify-content: center;
                    border-radius: 5px 5px 0px 5px;
                  "
                  >最新</span
                >快件到达【龙岗杨美服务点】
              </div>
              <div>2023/3/4 09:13:49</div>
            </div>
            <i
              v-if="item != 20"
              style="
                width: 1px;
                height: 30px;
                background: #e6e7e9;
                position: absolute;
                left: 7px;
                top: 34px;
              "
            />
          </div>
        </el-scrollbar>
      </div>
    </div>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, nextTick, toRaw, toRefs, onMounted, watch } from "vue";
import addSampleList from "./addSampleList";
import { ElMessageBox, ElMessage } from "element-plus";
import SelectFilterWarehouse from "@/components/SelectFilterWarehouse";
import SelectSupplie from "@/components/SelectSupplie";
import { sampleSave, samplEdit, detailDampleId, querySkuList } from "../api";
import { deepClone } from "../../../../utils";
let dialogVisible = ref(false);
const logisticsVisible = ref(false);
const addSampleListRef = ref(null);
const allAlign = ref("left");
const formRef = ref(null);
const tableRef = ref();

const props = defineProps({
  options: {
    type: Object,
    default: () => {
      return {};
    },
  },
});

// const sampleList = [
//   { label: "网络拿样", value: 0 },
//   { label: "线下拿样", value: 1 },
//   { label: "海外拿样", value: 2 },
//   { label: "供应商送样", value: 3 },
//   { label: "供应商借样", value: 4 },
// ];

const formRule = reactive({
  purchaser_id: [{ trigger: "change", required: true, message: "请选择采购人员" }],
});

const data = reactive({
  form: {
    is_purchase: 0,
    sample_type: 0,
    purchaser_id: "", // 采购人员id
    warehouse_id: "", // //收货仓库id
    supplier_id: "", //供应商id
    freight: "", //运费
    other_fee: "", //其它费用
    procurement_remarks: "", //备注信息
    expected_delivery_time: "", //预计到货时间
    tracking_nums: [],
  },
  title: "新增",
  handleType: null,
  load: false,
  loading: false,
});

const { form, title, handleType, load, loading } = toRefs(data);

const formOne = ref({
  purchase_id: "", // 采购单号 （暂未提供）
  materialFlowInp: "", // 物流追踪号输入（暂未提供）
  materialFlow: "", //  // 物流追踪号选项（暂未提供）
  total_amount: "", //  总金额
});

const totalSummer = computed(() => {
  if (!form.value.product_list) return 0;
  const tableData = form.value.product_list;
  const { freight, other_fee } = form.value;
  const tableQuoteNum = tableData.reduce((pre, cur) => {
    const { purchase_quantity, purchase_price } = cur;
    pre += Number(purchase_quantity) * Number(purchase_price);
    return pre;
  }, 0);
  return (tableQuoteNum + Number(freight) + Number(other_fee)).toFixed(2);
});

const sampleSaveFun = () => {
  const formData = deepClone(form.value);
  formRef.value.validate((flag) => {
    if (flag) {
      // 编辑状态下的提交
      if (!formData.supplier_id) {
        ElMessage.error("暂未获取到供应商信息, 请维护后再进行保存");
        return;
      }
      loading.value = true;

      if (formData.id) {
        samplEdit(toRaw(formData))
          .then((e) => {
            ElMessage({
              message: "编辑样品单成功",
              type: "success",
            });
            if (formData.is_purchase) {
              emits("createPurchase", formData.id);
            }
            handleClose();
          })
          .finally(() => {
            loading.value = false;
          });
      } else {
        sampleSave(toRaw(formData))
          .then((res) => {
            if (formData.is_purchase) {
              emits("createPurchase", res.id);
            }
            ElMessage({
              message: "新增样品单成功",
              type: "success",
            });
            handleClose();
          })
          .finally(() => {
            loading.value = false;
          });
      }
    }
  });
};

const logisticsVisDel = (index) => {
  ElMessageBox.confirm("确定删除么")
    .then(() => {
      form.value.tracking_nums.splice(index, 1);
    })
    .catch(() => {});
};
const delFun = (idx) => {
  ElMessageBox.confirm("确定删除么")
    .then(() => {
      form.value.product_list.splice(idx, 1);
    })
    .catch(() => {});
};

const statusMap = new Map([
  ["add", "新增样品单"],
  ["edit", "编辑样品单"],
  ["view", "查看样品单"],
]);

const open = async (type, id) => {
  if (!load.value) {
    load.value = true;
    await 1;
  }
  title.value = statusMap.get(type);
  handleType.value = type;
  dialogVisible.value = true;
  initForm();

  form.value.purchaser_id = window.userInfo.user.user_id;
  // 处理产品列表生成样品单
  if (id && type === "add") {
    paramsSampleList(id);
  } else if (id) {
    getDetail(id);
  }
};

const getDetail = async (id) => {
  try {
    const res = await detailDampleId(id);
    form.value = res.data;
  } catch (e) {
    throw Error(e);
  }
};

const addSampleListFun = () => {
  nextTick(() => {
    addSampleListRef.value.clearSelectEvent();
    addSampleListRef.value.open();
  });
};
const goFun = () => {
  window.open("https://www.kuaidi100.com/", "_blank");
};

const handleSearchOrder = () => {
  ElMessage.warning("获取物流轨迹数据失败，请手动查询!");
};

// 添加商品
const addSampleListQuery = (data) => {
  const product_list = data.map((item, idx) => {
    return {
      serial_num: idx,
      goods_spu: item.spu,
      goods_sku: item.sku,
      spu_category: item.spu_category,
      custom_sku: item.custom_sku,
      sku_cn_title: item.sku_cn_title,
      purchase_price: item.supplier_quotation,
      purchase_amount: item.supplier_quotation,
      purchase_quantity: 1,
      attr_img: item.attr_img,
      attr_img_watermark: item.attr_img_watermark,
      supplier_quotation: item.supplier_quotation,
      purchase_untaxed_price: item.purchase_untaxed_price,
      unit_price_tax: item.unit_price_tax,
      supplier_id: item.goods_sku_supplier?.supplier_id,
      purchaser_id: item.purchaser_id,
    };
  });
  form.value.product_list.push(...product_list);
  if (!form.value.supplier_id) {
    form.value.supplier_id = form.value.product_list[0].supplier_id;
  }
  form.value.purchaser_id = window.userInfo.user.user_id;
};

const checkArray = (arr) => {
  // 检查数组长度是否大于0
  if (arr.length === 0) {
    return false;
  }
  // 获取第一个非零元素作为默认值
  let defaultSupplierId = 0;
  for (let i = 0; i < arr.length; i++) {
    if (arr[i].purchaser_id !== 0) {
      defaultSupplierId = arr[i].purchaser_id;
      break;
    }
  }

  // 检查数组中的元素是否都与默认值相同且不为0
  for (let i = 0; i < arr.length; i++) {
    if (arr[i].purchaser_id !== defaultSupplierId || arr[i].purchaser_id === 0) {
      return false;
    }
  }

  return true;
};

const paramsSampleList = (sku_id) => {
  querySkuList({
    sku_id,
    pageSize: 1000,
  }).then((res) => {
    form.value.product_list = res.data.map((e, idx) => {
      return {
        serial_num: idx,
        goods_spu: e.spu,
        goods_sku: e.sku,
        spu_category: e.spu_category,
        custom_sku: e.custom_sku,
        sku_cn_title: e.sku_cn_title,
        purchase_amount: 0,
        purchase_price: e.supplier_quotation,
        purchase_quantity: 1,
        attr_img: e.attr_img,
        supplier_quotation: e.supplier_quotation,
        purchase_untaxed_price: e.purchase_untaxed_price,
        unit_price_tax: e.unit_price_tax,
        supplier_id: e.goods_sku_supplier?.supplier_id,
        purchaser_id: e.purchaser_id,
      };
    });
    form.value.supplier_id = form.value.product_list[0].supplier_id;
    // form.value.purchaser_id = checkArray(form.value.product_list)
    //   ? Number(form.value.product_list[0].purchaser_id) || window.userInfo.user.user_id
    //   : window.userInfo.user.user_id;
  });
};

const handleClose1 = (done) => {
  done();
};
const handleClose = (op) => {
  initForm();
  if (op) {
    form.is_purchase = 0;
  } else {
    emits("query");
  }
  dialogVisible.value = false;
};

const entryNumber = () => {
  if (!formOne.value.materialFlowInp) {
    ElMessage.error("请输入物流单号");
    return;
  }
  form.value.tracking_nums.push({
    cogistics_tracking_number: formOne.value.materialFlowInp,
  });
};

const initForm = () => {
  form.value = {
    is_purchase: 0,
    sample_type: 0,
    purchaser_id: "", // 采购人员id
    warehouse_id: "", // //收货仓库id
    supplier_id: "", //供应商id
    freight: "", //运费
    other_fee: "", //其它费用
    procurement_remarks: "", //备注信息
    expected_delivery_time: "", //预计到货时间
    tracking_nums: [],
    product_list: [],
  };
};

const emits = defineEmits(["query", "createPurchase"]);
defineExpose({ open });

const calculatePrice = (row) => {
  row.purchase_amount = (
    Number(row.purchase_quantity) * Number(row.purchase_price)
  ).toFixed(2);
  return row.purchase_amount;
};
</script>
<style lang="scss" scoped>
:deep(.inpselect .el-input__wrapper, .inp .el-input__wrapper) {
  border-radius: 4px 0 0 4px;
  height: 40px;
}

:deep(.inp .el-input__wrapper) {
  border-radius: 0;
  height: 40px;
}

.sampleTitle {
  position: relative;
  font-size: 16px;
  margin: 6px 6px 6px 0;
  padding-left: 6px;

  &::after {
    content: " ";
    height: 60%;
    width: 2px;
    position: absolute;
    left: 0;
    top: 20%;
    align-items: center;
    background-color: #3366f1;
  }
}

.flex1 {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.triangle {
  &:before {
    width: 0px;
    height: 0px;
    content: "";
    border-top: 10px solid transparent;
    border-bottom: 10px solid transparent;
    border-right: 10px solid #fff;
    position: absolute;
    top: 20px;
    left: -10px;
  }
}
</style>
